package com.yupi.springbootinit.bizmq;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.api.AliAPI;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.utils.AliResponseUtils;
import com.yupi.springbootinit.utils.ExcelUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;


/**
 * @Author FengHuan Wang
 * @Date 2025/2/14 15:44
 * @Version 1.0
 */
@Slf4j
@Component
public class BiConsumer {

    @Resource
    private ChartService chartService;

    @SneakyThrows
    @RabbitListener(queues = {"yubi"}, ackMode = "MANUAL")
    public void receive(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        log.info("收到消息：{}", message);
        if (StringUtils.isBlank(message)){
            //如果失败，消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw  new BusinessException(ErrorCode.TOO_MANY_REQUEST, "消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null){
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        // 先修改图表任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b){
            channel.basicNack(deliveryTag, false, false);
            this.handleUpdateErr(chart.getId(),"更新图表执行中状态失败");
            return;
        }
        //调用AI
        //向ai提问的内容
        GenerationResult result = null;
        try {
            result = AliAPI.callWithMessage(this.userInputBuilder(chart));
        } catch (NoApiKeyException e) {
            log.error("ApiKey未找到");
        } catch (InputRequiredException e) {
            log.error("输入内容异常");
        }
        log.info("用户："+ chart.getUserId() +"正在调用阿里云通义大模型生成内容。。。");
        String answer = JsonUtils.toJson(result);
        List<String> format = AliResponseUtils.format(answer);
        Chart updateChartRes = new Chart();
        updateChartRes.setId(chart.getId());
        updateChartRes.setStatus("success");
        updateChartRes.setGenChart(format.get(0));
        updateChartRes.setGenResult(format.get(1));
        boolean res = chartService.updateById(updateChartRes);
        if (!res){
            this.handleUpdateErr(chart.getId(), "更新图表成功状态失败");
        }
        // 消息确认
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 构建用户输入
     * @param goal
     * @param chartType
     * @param multipartFile
     * @return
     */
    public String userInputBuilder(Chart chart) {
        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("你是一个数据分析师，接下来我会给你我的分析目标和原始数据，请告诉我分析结论：").append("\n");
        //拼接分析目标
        String userGoal = chart.getGoal();
        if (StringUtils.isNoneBlank(chart.getChartType())) {
            userGoal += "请使用" + chart.getChartType();
        }
        userInput.append(userGoal).append("\n");
        //转csv,压缩后的数据
        String csv = chart.getChartData();
        userInput.append("原始数据(csv格式的原始数据，用,作为分隔符)：").append(csv).append("\n");
        userInput.append("请根据这两部分内容，按照以下指定格式生成内容（此外不要输出任何多余的开头、结尾、注释）\n" +
                        "【【【【【\n" +
                        "前端 Echarts V5 的 option 配置对象js代码，合理地将数据进行可视化，不要生成任何多余的注释\n" +
                        "【【【【【\n")
                .append("<<<<<\n"+
                        "你的数据分析结果,要尽可能的详细，越详细越好\n"+
                        "<<<<<\n");
        return userInput.toString();
    }
    /**
     * 状态更新处务处理
     * @param chartId
     * @param execMessage
     */
    public void handleUpdateErr(Long chartId, String execMessage){
        Chart updateChartRes = new Chart();
        updateChartRes.setId(chartId);
        updateChartRes.setStatus("failed");
        updateChartRes.setExecMessage(execMessage);
        boolean update = chartService.updateById(updateChartRes);
        if (!update){
            log.error("更新图表失败状态失败");
        }
    }
}
